package com.sskj.givecoin.v.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.view.TimePickerView;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.givecoin.R;
import com.sskj.givecoin.adapter.slimadapter.IViewInjector;
import com.sskj.givecoin.adapter.slimadapter.SlimAdapter;
import com.sskj.givecoin.adapter.slimadapter.SlimInjector;
import com.sskj.givecoin.common.App;
import com.sskj.givecoin.common.Constants;
import com.sskj.givecoin.common.decoration.DividerLineItemDecoration;
import com.sskj.givecoin.m.bean.FabiPublishListBean;
import com.sskj.givecoin.mvchelper.ModelRx2DataSource;
import com.sskj.givecoin.p.fragment.FabuRecordPresenter;
import com.sskj.givecoin.utils.TimeFormatUtil;
import com.sskj.givecoin.v.activity.FabiSellListActivity;
import com.sskj.givecoin.v.base.BaseFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 发布记录
 */
public class FabuRecordFragment extends BaseFragment<FabiSellListActivity, FabuRecordPresenter> {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    //    @BindView(R.id.ll_time)
//    LinearLayout llTime;
    private SlimAdapter<FabiPublishListBean> slimAdapter;
    private PopupWindow popupWindow;
    private boolean isStart = true;
    private TimePickerView startPicker;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private View popupView;
    private boolean isBuy;
    private MVCCoolHelper<List<FabiPublishListBean>> mvcCoolHelper;
    private int curPos;
    private AlertDialog tipDialog;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_fabu_record;
    }

    @Override
    public FabuRecordPresenter getPresenter() {
        return new FabuRecordPresenter();
    }

    @Override
    public void initData() {
        HashMap<String, String> statusMap = new HashMap<>();
        HashMap<String, String> statusControlMap = new HashMap<>();
        statusMap.put("1", App.INSTANCE.getString(R.string.strFabiSellListActivity201));
        statusMap.put("2", App.INSTANCE.getString(R.string.strFabiSellListActivity203));
        statusMap.put("3", App.INSTANCE.getString(R.string.strFabiSellListActivity205));
        statusControlMap.put("1", App.INSTANCE.getString(R.string.strFabiSellListActivity207));
        statusControlMap.put("2", App.INSTANCE.getString(R.string.strFabiSellListActivity203));
        statusControlMap.put("3", App.INSTANCE.getString(R.string.strFabiSellListActivity205));
//        tvTitle.setText(isBuy ? App.INSTANCE.getString(R.string.strFabiSellListActivity215) : App.INSTANCE.getString(R.string.strFabiSellListActivity216));
//        ClickUtil.click(300, tvFilter, this::showTimePop);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getContext())
                .setFirstDraw(false)
                .setDividerColor(ContextCompat.getColor(getContext(), R.color.app_f2f))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(getContext(), 3)));
        slimAdapter = SlimAdapter.create().register(R.layout.recy_item_fabi_sell_list, new SlimInjector<FabiPublishListBean>() {
            @Override
            public void onInject(FabiPublishListBean data, IViewInjector injector) {

                injector
//                        .text(R.id.tv_id_code, data.getOrder_no())
//                        .text(R.id.tv_status, statusMap.get(data.getStatus()))
                        .text(R.id.price_tv, isBuy ? App.INSTANCE.getString(R.string.xmlrecy_item_fabi_sell_list79) : App.INSTANCE.getString(R.string.fabi_sell_price2))
                        .text(R.id.num_tv, isBuy ? App.INSTANCE.getString(R.string.xmlrecy_item_fabi_sell_list50) : App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment219))
                        .text(R.id.price_tv_end, isBuy ? App.INSTANCE.getString(R.string.xmlrecy_item_fabi_sell_list92) : App.INSTANCE.getString(R.string.xmlrecy_item_fabi_sell_list93))
                        .text(R.id.tv_price, "¥" + data.getPrice())
                        .text(R.id.tv_all_price, "¥" + data.getTotalprice())
                        .text(R.id.tv_detail, statusControlMap.get(data.getStatus()))
                        .text(R.id.tv_price, "¥" + data.getPrice())
                        .text(R.id.tv_all_price, "¥" + data.getTotalprice())
                        .text(R.id.tv_num, data.getTrans_num() + "USDT")
                        .text(R.id.tv_time, data.getAdd_time())
                        .text(R.id.tv_min_price, "¥" + data.getMin_price())
                        .text(R.id.tv_max_price, "¥" + data.getMax_price())
                        .visibility(R.id.iv_wechat, "1".equals(data.getPay_wx()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_bank, "1".equals(data.getPay_backcard()) ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_alipay, "1".equals(data.getPay_alipay()) ? View.VISIBLE : View.GONE)
                        .clicked(R.id.tv_detail, (v) -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            if ("1".equals(data.getStatus())) {
                                showCancelTip();
                            }
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<FabiPublishListBean> dataSource =
                new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<FabiPublishListBean>)
                        page -> mPresenter.getData(page, isBuy, tvStartTime == null ? "" : TimeFormatUtil.parseLongE(tvStartTime.getText().toString() + " 00:00:00"), tvEndTime == null ? "" : TimeFormatUtil.parseLongE(tvEndTime.getText().toString() + " 23:59:59")), 10);
        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(dataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        mvcCoolHelper.refresh();
    }

    /**
     * 显示撤单提示
     */
    private void showCancelTip() {
        if (tipDialog == null) {
            tipDialog = new AlertDialog.Builder(getContext())
                    .setTitle(App.INSTANCE.getString(R.string.strFabiSellListActivity223))
                    .setMessage(App.INSTANCE.getString(R.string.strFabiSellListActivity224))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strFabiSellListActivity225), (dialog, which) -> {
                        dialog.dismiss();
                        mPresenter.cancelOrder(isBuy, slimAdapter.getDataItem(curPos).getId());
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strFabiSellListActivity226), (dialog, which) -> dialog.dismiss()).create();
        }
        try {

            //标题
            tipDialog.show();
            tipDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
            tipDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
            TextView tvTitle = (TextView) tipDialog.getWindow().findViewById(R.id.alertTitle);
            tvTitle.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.black));
        } catch (Exception e) {

        }
    }

    /**
     * 显示时间选择弹窗
     */
//    private void showTimePop() {
//        if (popupWindow != null && popupWindow.isShowing()) {
//            popupWindow.dismiss();
//        } else {
//            popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_fabi_time_select, null);
//            tvStartTime = popupView.findViewById(R.id.tv_start_time);
//            tvEndTime = popupView.findViewById(R.id.tv_end_time);
//            ClickUtil.click(popupView.findViewById(R.id.tv_apply), () -> {
//                popupWindow.dismiss();
//                mvcCoolHelper.refresh();
//            });
//            ClickUtil.click(popupView.findViewById(R.id.tv_cancel), () -> {
//                tvStartTime.setText("");
//                tvEndTime.setText("");
//            });
//            initTime();
//            View view = popupView.findViewById(R.id.view);
//            ClickUtil.click(view, () -> {
//                popupWindow.dismiss();
//            });
//
//            popupWindow = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//            popupWindow.setContentView(popupView);
////          popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
////          popupWindow.setOutsideTouchable(true);
////          popupWindow.setAnimationStyle(R.style.AnimDown);
////          popupWindow.setClippingEnabled(true);
//            if (Build.VERSION.SDK_INT > 24) {
//                Rect rect = new Rect();
//                llTime.getGlobalVisibleRect(rect);
//                int h = llTime.getResources().getDisplayMetrics().heightPixels - rect.bottom;
//                popupWindow.setHeight(h);
//            }
//            popupWindow.showAsDropDown(llTime);
//        }
//
//
//    }

//    private void initTime() {
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.DAY_OF_YEAR, -7);
//        tvStartTime.setText(TimeFormatUtil.SF_FORMAT_B.format(instance.getTime()));
//        tvEndTime.setText(TimeFormatUtil.SF_FORMAT_B.format(Calendar.getInstance().getTime()));
//        ClickUtil.click(tvStartTime, () -> showTime(true));
//        ClickUtil.click(tvEndTime, () -> showTime(false));
//    }


//    private void showTime(boolean isStart) {
//        this.isStart = isStart;
//        startPicker = new TimePickerBuilder(getContext(), (date, v) -> {
//            if (this.isStart) {
//                tvStartTime.setText(TimeFormatUtil.limitMaxDate(date));
//            } else {
//                tvEndTime.setText(TimeFormatUtil.limitMaxDate(date));
//            }
//        }).setDecorView((ViewGroup) popupView).build();
//        try {
//            Date parse = TimeFormatUtil.SF_FORMAT_B.parse(isStart ? tvStartTime.getText().toString() : tvEndTime.getText().toString());
//            Calendar instance = Calendar.getInstance();
//            instance.setTime(parse);
//            startPicker.setDate(instance);
//            startPicker.show();
//        } catch (ParseException e) {
//            startPicker.show();
//
//        }
//    }
    public void refresh() {
        mvcCoolHelper.refresh();
    }

    public void delete() {
        slimAdapter.getData().remove(curPos);
        slimAdapter.notifyItemRemoved(curPos);
    }

    public static FabuRecordFragment newInstance(boolean isBuy) {
        Bundle args = new Bundle();
        args.putBoolean(Constants.IS_BUY, isBuy);
        FabuRecordFragment fragment = new FabuRecordFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView() {
        super.initView();
        isBuy = getArguments().getBoolean(Constants.IS_BUY);
    }
}
